#! env node

const fs = require("fs");
const path = require("path");

class createTracker {
    constructor(genePath, geneName, geneData) {
        this.path = genePath;
        this.name = geneName;
        this.data = geneData;
        //数据初步处理
        this.dataTag = typeof this.data.task.tag === 'object' ? this.data.task.tag : []
        this.fun = {
            before: `
export const config = {
  eventGroup: '${this.data.task.identify}',
  name: '${this.data.task.name}',
  identify: '${this.data.group.identify}',
  eventTags: ['${this.dataTag}']
};            

export default function createTracker(report, getDiffRouteTime) {
  return {`,
            after: `
   }
}\n`
        };
        this.result = false;
    }

    async init() {
        let main = this.fun.before + await createTracker.geneFunction(this.data.point) + this.fun.after;
        // console.log(main);
        this.write(path.join(this.path, this.name), main);
    }

    write(item, content) {
        fs.writeFile(item, content, (err) => {
            if (err) throw err;
            else this.result = true
        })
    }

    //生成外围函数
    static async geneFunction(list) {
        let content = '';
        for (let i = 0; i < list.length; i++) {
            let item = list[i];
            let itemEvd = item['ev_d'] || [];
            let evens = {content: ''}
            let temp = `
        ${createTracker.toCamel(item['ev_n'])}:function() {
            report({
                eventName: '${item['ev_n']}',
                eventDescription: '${item['ev_desc']}'
            });
        },`;
            if (itemEvd.length) {
                evens = await createTracker.geneCore(itemEvd);
                temp = `
        //${evens.descs}
        ${createTracker.toCamel(item['ev_n'])}:function(${evens.params}) {
            report({
                eventName: '${item['ev_n']}',
                eventDescription: '${item['ev_desc']}',
                eventDataValue: {
                ${evens.content}
                }
            });
        },`;
            }
            content = content + temp
        }
        return content
    }

    //生成核心
    static geneCore(evens) {
        let content = '';
        let params = '';
        let descs = ''
        for (let i = 0; i < evens.length; i++) {
            let item = evens[i];
            if (item['identify']) {
                let key = item['identify'];
                if (key.match(/\./)) key = key.split('.')[1];
                let value = createTracker.toCamel(key);
                let param = value + ',';
                if (key === 'td_pl') {
                    value = 'getDiffRouteTime()';
                    param = ''
                }
                let temp = `    ${key} : ${value},
                `;
                let desc = value + '(' + item['desc'] + ')'
                //handle single or last
                if (evens.length === 1 || i === evens.length - 1) {
                    temp = `    ${key} : ${value}`;
                    param = param.split(',')[0]
                }
                params = params + param;
                content = content + temp;
                descs = descs + ' ' + desc;
            }
        }
        return {content, params, descs}
    }

    // 转驼峰
    static toCamel(str) {
        return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
            return $1 + $2.toUpperCase();
        });
    }


}

module.exports = createTracker;
